﻿using System;
using System.IO;
using System.Collections;
//using System.ComponentModel;
using System.Data;
//using System.Drawing;
//using System.Linq;
//using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Threading;
using System.ComponentModel;

namespace Release
{
    public partial class main_form : Form
    {
        #region memebers declaration
        public Configure iconfig = new Configure();
        private Release_Check active_rel;
        public static int fale_flag;
        private int lb_select;
        //private Boolean auto_sync;
        //private int sync_hour;
        //private int sync_minute;
        //private Boolean auto_sync_pattern;
        //private string sync_pattern;
        
        //private int auto_copy_flag;
        #endregion
        public main_form()
        {            InitializeComponent();
        Control.CheckForIllegalCrossThreadCalls = false;
        }
        #region private function declaration

        public void change_tsl_content(string s) {
            this.tsl_status.Text = s;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           fale_flag = 0;
            //Boolean startNow =false;
           this.SizeChanged += new System.EventHandler(this.form1_sizechanged);
           this.ccb_folders.SelectedIndexChanged += new EventHandler(this.ccb_folders_item_change);
           this.cbb_project_name.SelectedIndexChanged += new EventHandler(this.ccb_project_name_item_change);
           this.lb_folders.DoubleClick  += new EventHandler(this.lb_double_click);
           this.tstb_sync_time.TextChanged += new EventHandler(this.tstb_sync_time_content_change);
           this.tstb_copy_pattern.TextChanged  += new EventHandler(this.tstb_sync_pattern_content_change);

           this.lv_release_display.DoubleClick += new EventHandler(this.lv_double_click);

           Application.ApplicationExit += new EventHandler(this.before_close);

           this.lv_release_display.Columns.Add("Time");
           this.lv_release_display.Columns.Add("Name");
           this.lv_release_display.Columns.Add("Access Time");
           this.lv_release_display.Columns.Add("Source");
           this.lv_release_display.View = View.Details;

           if (iconfig.read_cfg())
           {
               this.cbb_project_name.Text = iconfig.act_proj_name;
               this.update_lb_folders(iconfig.active_proj().src_folders);
               this.lb_select = 1;
               if (iconfig.active_proj().auto_sync)
               {
                   this.tsmi_copy_time_setting.CheckState = CheckState.Checked;
                   this.tstb_sync_time.Visible = true;
                   this.iconfig.auto_sync_flag = "1";
                   this.tstb_sync_time.Text = iconfig.active_proj().sync_hour.ToString("00") + ":" + iconfig.active_proj().sync_minute.ToString("00");
               }
               else {
                   this.tsmi_copy_time_setting.CheckState = CheckState.Unchecked;
                   this.tstb_sync_time.Visible = false;
                   this.tstb_sync_time.Text = "00:00";
                   this.iconfig.auto_sync_flag = "0";
               }
               if (iconfig.active_proj().auto_sync_pattern)
               {
                   this.tsmi_copy_pattern_settings.CheckState = CheckState.Checked;
                   this.tstb_copy_pattern.Visible = true;
                   this.tstb_copy_pattern.Text = iconfig.active_proj().sync_pattern;
               }
               else {
                   this.tsmi_copy_pattern_settings.CheckState = CheckState.Unchecked;
                   this.tstb_copy_pattern.Visible = false;
                   this.tstb_copy_pattern.Text = "";
               }

               //if (iconfig.auto_sync_flag == "1")
               //{
               //    this.checkBox1.Checked = true;
               //}
               //else {
               //    this.checkBox1.Checked = false;
               //}
               this.check_server_and_copy(false);
           }
           else {
               this.cbb_project_name.Text = iconfig.act_proj_name;
               this.lb_select = 1;
           }
           System.Timers.Timer aTimer = new System.Timers.Timer();
           aTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
           aTimer.Interval = 60000;
           aTimer.Enabled = true; 
        }


        private void form1_sizechanged(Object sender, EventArgs e){
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.active_rel.form_minimized = true;
                this.Hide();
                notifyIcon1.ShowBalloonTip(1000, "Notice", "I will run in backgraound", ToolTipIcon.Info);
                this.notifyIcon1.Visible = true;
            }
            else {
                this.active_rel.form_minimized = false;
            }
        }

        private void explore_server()
        {
            active_rel = new Release_Check(this.iconfig);
            active_rel.change_content += new Release_Check.notify_icon_content_change(this.update_notifyicon_content);
            if (active_rel.comp_server_local())
            {
                this.lv_update(active_rel);
                //this.status_label_update("new release detected on server.");
            //this.label_status.Text = ;
            }
            else
            {
                //this.status_label_update("currently no new release detected on server.");
                //this.label_status.Text = "currently no new release detected on server.";
                //MessageBox.Show("currently no new release detected on server.", "Info");

            }
            //File.Delete(iconfig.active_proj().records_file);
            #region change ID 20130001 Action: outcomment active_rel.save_local();
            //Date:         20130217
            //Version:      v1.01 
            //Action:       outcomment active_rel.save_local();    
            //Reason:       made the change that only after copied the specific folders then we start to save the historical folders.
            //active_rel.save_local();
            #endregion 
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Focus();
            this.notifyIcon1.Visible = false; 
        }

        private void lv_update(Release_Check rel)
        {
            this.lv_release_display.Items.Clear();
            foreach (DataRow tmp_dr in rel.get_diff_dt().Rows) { 
                ListViewItem record =new ListViewItem(System.DateTime.Now.ToString());
                record.SubItems.Add(tmp_dr["release_name"].ToString());//第一行第二列
                record.SubItems.Add(tmp_dr["release_time"].ToString());//第一行第三列
                record.SubItems.Add(tmp_dr["source_folder"].ToString());
                this.lv_release_display.Items.Add(record);
                for (int i = 0; i < this.lv_release_display.Columns.Count; i++) {
                    this.lv_release_display.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                }
            }
            this.Update();
        }

        private void before_close(Object sender, EventArgs e)
        {
            //this.active_rel.save_local();
            iconfig.write_new_cfg();
        }

        private void ccb_folders_item_change(object sender,EventArgs e){
            string selected;
            selected = this.ccb_folders.Text;

            if (fale_flag != 0) {
                return;
            }
            this.lb_folders.Items.Clear();
            if (selected == "Source")
            {
                this.lb_select = 1;
                this.update_lb_folders(iconfig.active_proj().src_folders);
            }
            else {
                this.lb_select = 2;
                this.update_lb_folders(iconfig.active_proj().tgt_folders);
            }
            
        }

        private void b_add_folder_Click(object sender, EventArgs e)
        {
            string add_folder;
            add_folder = "";
            fale_flag = 0;
            //define an folder browser
            //add_folder = this.lb_source.SelectedValue.ToString();
            try { 
                if (iconfig.active_proj().src_folders.Count != 0 ){
                    this.folderBrowserDialog1.SelectedPath = iconfig.active_proj().src_folders[0].ToString();
                }
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK){
                    add_folder = folderBrowserDialog1.SelectedPath;
                }
            }catch(Exception err){
                MessageBox.Show(err.Message);
                return;
            }
            if (Directory.Exists(add_folder))
            {
                if (this.check_exist_folder(add_folder))
                {
                    MessageBox.Show("selected folder already existed!");
                    return;
                }
                else
                {
                    if (this.lb_select == 1)
                    {
                        iconfig.active_proj().add_src_folder(add_folder);
                        this.update_lb_folders(iconfig.active_proj().src_folders);
                        this.check_server_and_copy(false);
                    }
                    else
                    {
                        iconfig.active_proj().add_tgt_folder(add_folder);
                        this.update_lb_folders(iconfig.active_proj().tgt_folders);
                    }
                }

            }
            else {
                fale_flag = 1;
                return;
            }
        }

        private void b_del_folder_Click(object sender, EventArgs e)
        {
            //Object tmp_obj = new Object();
            if (this.lb_folders.SelectedItems.Count == 0) {
                MessageBox.Show("You forget to select folder.");
                return;
            }
            string del_folder;
            del_folder = this.lb_folders.SelectedItem.ToString();

            Configure.info_proj tmp_p = new Configure.info_proj();
            if (this.lb_select == 1)
            {
                tmp_p = iconfig.active_proj();
                tmp_p.del_src_folder(del_folder);
                iconfig.del_obj(iconfig.active_proj());
                iconfig.add_obj(tmp_p);
                this.lb_folders.Items.Clear();
                foreach (string s in iconfig.active_proj().src_folders) {
                    this.lb_folders.Items.Add(s);
                }
                this.lb_folders.Refresh();
            }
            else {
                tmp_p = iconfig.active_proj();
                tmp_p.del_tgt_folder(del_folder);
                iconfig.del_obj(iconfig.active_proj());
                iconfig.add_obj(tmp_p);
                this.lb_folders.Items.Clear();
                foreach (string s in iconfig.active_proj().tgt_folders)
                {
                    this.lb_folders.Items.Add(s);
                }
                this.lb_folders.Refresh();
            }
            tmp_p = null;
        }

        private void update_lb_folders(ArrayList folders) {
            this.lb_folders.Items.Clear();
            foreach (string s in folders) {
                this.lb_folders.Items.Add(s);
            }
            this.lb_folders.Refresh();
            //this.check_server_and_copy(iconfig.auto_sync_flag);
        }

        private Boolean check_exist_folder(string s) {
            if (this.lb_select == 1)
            {
                foreach (string existed in iconfig.active_proj().src_folders)
                {
                    if (s == existed)
                    {
                        return true;
                    }
                }
                return false;
            }
            else {
                foreach (string existed in iconfig.active_proj().tgt_folders)
                {
                    if (s == existed)
                    {
                        return true;
                    }
                }
                return false;
            }
        }

        private void ccb_project_name_item_change(object sender, EventArgs e) {
            iconfig.act_proj_name = this.cbb_project_name.Text;
            if (fale_flag != 0)
            {
                return;
            }
            if (this.lb_select == 1)
            {
                this.update_lb_folders(iconfig.active_proj().src_folders);
                this.lb_folders.Refresh();
            }
            else {
                this.update_lb_folders(iconfig.active_proj().tgt_folders);
                this.lb_folders.Refresh();
            }
            
        }

        private void tstb_sync_time_content_change(object sender, EventArgs e) {
            if (this.tstb_sync_time.Text.Length > 4) {
                this.iconfig.active_proj().sync_hour = Convert.ToInt32(this.tstb_sync_time.Text.Split(':')[0]);
                this.iconfig.active_proj().sync_minute = Convert.ToInt32(this.tstb_sync_time.Text.Split(':')[1]);
            }
        }

        private void tstb_sync_pattern_content_change(object sender, EventArgs e) {
            this.iconfig.active_proj().sync_pattern = this.tstb_copy_pattern.Text;
        }

        private void lb_double_click(object sender, EventArgs e) {
            string folder;
            if (this.lb_folders.SelectedItems.Count == 0) {
                MessageBox.Show("please select a folder.");
                return;
            }else{
                folder = this.lb_folders.SelectedItem.ToString();
                System.Diagnostics.Process.Start(folder);
            }
        }

        private void lv_double_click(object sender, EventArgs e) {
            string folderToOpen;
            //ListViewItem selectedItem = new ListViewItem();
            try
            {
                if (lv_release_display.SelectedItems.Count > 0)
                {
                    foreach (ListViewItem selectedItem in lv_release_display.SelectedItems)
                    {
                        folderToOpen = selectedItem.SubItems[3].Text + "\\" + selectedItem.SubItems[1].Text ;
                        System.Diagnostics.Process.Start(folderToOpen);
                    }
                }
            }
            catch (Exception err) {
                MessageBox.Show(err.Message);
                return;
            }
        }

        //private void b_copy_to_target_Click(object sender, EventArgs e)
        //{
        //    if (this.lv_release_display.SelectedItems.Count == 0)
        //    {
        //        MessageBox.Show("no releases selected! no copy action!");
        //    }
        //    else {
        //        Cursor.Current = Cursors.WaitCursor;
        //        //need to transfer the selected items to active_rel.xxxdt
        //        if (this.active_rel.diff_dt_clear())
        //        {
        //            foreach (ListViewItem selectedItem in lv_release_display.SelectedItems)
        //            {
        //                if (!this.active_rel.diff_dt_add_row(selectedItem.SubItems[1].Text, selectedItem.SubItems[2].Text, selectedItem.SubItems[3].Text)) {
        //                    MessageBox.Show("error add new dr to diff dt.");
        //                }
        //            }
        //        }
        //    }
            
        //    if (this.active_rel.get_diff_dt().Rows.Count == 0) {
        //        MessageBox.Show("no releases need to be copied.");
        //        return;
        //    }
        //    if (this.active_rel.copy_diff_folders() == 0)
        //    {
        //        this.label_status.Text = "problem while copying folder.";
        //    }
        //    // after copy done, need to update the display on listview.
        //    // first save local diff_dt.
        //    // second check server again and update the lv.
        //    active_rel.save_local();
        //    this.check_server_and_copy(iconfig.auto_sync_flag);
        //    Cursor.Current = Cursors.Default;
        //}

        //private void checkBox1_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (this.checkBox1.Checked)
        //    {
        //        this.iconfig.auto_sync_flag = "1";
        //    }
        //    else {
        //        this.iconfig.auto_sync_flag = "0";
        //    }
        //}

        private void check_server_and_copy(Boolean copy_now ,string pattern = "", Boolean ignore_pattern = true)
        {
            int result;
            this.explore_server();
            if (copy_now == true)
            {
                result = active_rel.copy_diff_folders(pattern,ignore_pattern);
                if (result == 0)
                {
                    //this.status_label_update("problem while copying the folder");
                    //this.label_status.Text = "problem while copying the folder";
                }
                else {
                    if (result > 1) {
                        //this.status_label_update("new release detected and copied");
                        //this.label_status.Text = "new release detected and copied";
                    }
                }
            }
            else
            {
                if (this.tsl_status.Text.Contains(" no "))
                {
                    ;
                }
                else {
                    //this.tsl_status.Text += " not copied.";
                }

            }
        }

        private void update_notifyicon_content(string s )
        {
            this.notifyIcon1.Text = s;
            notifyIcon1.ShowBalloonTip(1000, "Notice", s, ToolTipIcon.Info);
        }

        //private void update_status_label_content(string s){
        //    if (this.label_status.InvokeRequired)
        //    {
        //        SetTextCallback d = delegate(string str)
        //        {
        //            this.label_status.Text = str;
        //        };
        //        this.label_status.Invoke(d, s);
        //    }
        //    else {
        //        this.label_status.Text = s;
        //    }
        //   // this.label_status.Refresh();
        //}

        private void TimeEvent(object source, ElapsedEventArgs e) {
            int int_hour = e.SignalTime.Hour;
            int int_min = e.SignalTime.Minute;
            string pattern = iconfig.active_proj().sync_pattern;
            Boolean ignore_pattern = !iconfig.active_proj().auto_sync_pattern;

            int i_hour = iconfig.active_proj().sync_hour;
            int i_min = iconfig.active_proj().sync_minute;
            //this.ts_action_and_Settings.Refresh();
            if (int_hour == i_hour && int_min == i_min ) {
                Cursor.Current = Cursors.WaitCursor;
                this.check_server_and_copy(true, pattern, ignore_pattern);
                active_rel.save_local();
                this.check_server_and_copy(false);
                Cursor.Current = Cursors.Default;
            }
        }
        private delegate void SetTextCallback(string text);
        #region change ID 20130002 Action: add Toolsctrip for advanced use of setting the copy settings.
        //Date:         20130217
        //Version:      v1.01 
        //Action:       add private function tsl_copy_time_Click()    
        //Reason:       to add better user interaction. add toolstrip ts_action_and_Settings and relevant UI functions.
        private void tsl_copy_time_Click(object sender, EventArgs e)
        {
            if (tsmi_copy_time_setting.Checked == true)
            {
                tsb_copy_to_target.DropDownItems[1].Visible = true;
                tsb_copy_to_target.DropDownItems[2].Visible = true;
                this.iconfig.active_proj().auto_sync = true;
            }
            else
            {
                this.iconfig.active_proj().auto_sync = false;
                tsb_copy_to_target.DropDownItems[1].Visible = false;
                tsb_copy_to_target.DropDownItems[2].Visible = false;
            }
            tsb_copy_to_target.ShowDropDown();
        }

        private void tsmi_copy_pattern_settings_Click(object sender, EventArgs e)
        {
            if (tsmi_copy_time_setting.Checked == true)
            {
                tsb_copy_to_target.DropDownItems[3].Visible = true;
                this.iconfig.active_proj().auto_sync_pattern = true;
            }
            else {
                tsb_copy_to_target.DropDownItems[3].Visible = false ;
                this.iconfig.active_proj().auto_sync_pattern = false;
            }
            tsb_copy_to_target.ShowDropDown();
        }

        private void status_label_update(string s) {
            this.tsl_status.Text = s;
        }

        private void tsb_copy_to_target_ButtonClick(object sender, EventArgs e)
        {
            if (this.lv_release_display.SelectedItems.Count == 0)
            {
                MessageBox.Show("no releases selected! no copy action!");
            }
            else
            {
                Cursor.Current = Cursors.WaitCursor;
                //need to transfer the selected items to active_rel.xxxdt
                if (this.active_rel.diff_dt_clear())
                {
                    foreach (ListViewItem selectedItem in lv_release_display.SelectedItems)
                    {
                        if (!this.active_rel.diff_dt_add_row(selectedItem.SubItems[1].Text, selectedItem.SubItems[2].Text, selectedItem.SubItems[3].Text))
                        {
                            MessageBox.Show("error add new dr to diff dt.");
                        }
                    }
                }
            }

            if (this.active_rel.get_diff_dt().Rows.Count == 0)
            {
                MessageBox.Show("no releases need to be copied.");
                return;
            }
            if (this.active_rel.copy_diff_folders() == 0)
            {
                //this.status_label_update("problem while copying folder.");
                //this.label_status.Text = "problem while copying folder.";
            }
            else {
                //this.status_label_update("selected release copied.");
            }
            // after copy done, need to update the display on listview.
            // first save local diff_dt.
            // second check server again and update the lv.
            active_rel.save_local();
            this.check_server_and_copy(false);
            Cursor.Current = Cursors.Default;
        }
    }
        #endregion 
        #endregion
}